/**
 * 
 */
package org.xlab.baseframework.job;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.xlab.baseframework.common.entity.AbstractSystemBean;
import org.xlab.baseframework.domain.SystemWebServiceSession;
import org.xlab.baseframework.exception.RootUserNotFoundException;
import org.xlab.baseframework.exception.SystemRuntimeException;
import org.xlab.baseframework.exception.SystemWebServiceSessionNotFoundException;
import org.xlab.baseframework.service.api.ISystemWebServiceSessionService;

/**
 * 清理系统web service session
 * 
 * @author makubex
 *
 */
@Component
public class WSSessionCleaningJob extends AbstractSystemBean {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 428060615983818642L;
	
	private static final Logger log = Logger.getLogger(WSSessionCleaningJob.class);
	
	@Autowired(required = true)
	@Qualifier("bpf_systemWSSessionService")
	private ISystemWebServiceSessionService systemWebServiceSessionService;

	public void clean() {
		try {
			List<SystemWebServiceSession> activeSession = this.systemWebServiceSessionService.findAllActiveSession();
			log.debug(activeSession.size() + " session were found, now checking...");
			int deletedCount = 0;
			for (SystemWebServiceSession session : activeSession) {
				if (this.systemWebServiceSessionService.checkExpired(session.getSessionId())) {
					log.debug("Session["+session.getSessionId()+"] is expired, now cleaning...");
					this.systemWebServiceSessionService.deleteSession(session.getSessionId(), super.userService.getSystemRootUser());
					deletedCount++;
				} else {
					log.debug("Session["+session.getSessionId()+"] is still alive.");
				}
			}
			log.debug("Done! "+deletedCount+" session were deleted!");
		} catch (SystemWebServiceSessionNotFoundException e) {
			log.debug("No active session was found right now.");
		} catch (RootUserNotFoundException e) {
			log.error("Can not find system root user informaion. Please contact system administrator.");
			throw new SystemRuntimeException(e);
		}
	}

	/**
	 * @return the systemWebServiceSessionService
	 */
	public ISystemWebServiceSessionService getSystemWebServiceSessionService() {
		return systemWebServiceSessionService;
	}

	/**
	 * @param systemWebServiceSessionService the systemWebServiceSessionService to set
	 */
	public void setSystemWebServiceSessionService(
			ISystemWebServiceSessionService systemWebServiceSessionService) {
		this.systemWebServiceSessionService = systemWebServiceSessionService;
	}
}
